package com.kafka.kafkademo.kafka;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;

/**
 * @description
 * @author: yx-0173
 * @date: 2021-06-02 14:48
 **/
@Component
@Slf4j
public class KafkaProducer {

    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;

    public static final String TOPIC = "yzr";


    /**
     * kafka发送消息
     *
     * @param obj 接收参数
     */
    public void send(Object obj) {
        String jsonString = JSONObject.toJSONString(obj);
        log.info("准备发送消息为：{}", jsonString);
        // 发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC, obj);
        // 回调
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(@NotNull Throwable throwable) {
                // 发送失败的处理
                log.info("{}-生产者发送消息失败:{}", TOPIC, throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                // 发送成功的处理
                log.info("{}-生产者发送消息成功:{}", TOPIC, stringObjectSendResult.toString());
            }
        });
    }
}
